<?php

class Ebx_Helper_GroupArray implements Ebx_Helper_Interface {

	protected $_siteFormatShort = null;
	protected $_siteFormatLong = null;
	protected $_options = array();

	function __construct() {
		$this->_siteFormatShort = CSite::GetDateFormat('SHORT', SITE_ID);
		$this->_siteFormatLong = CSite::GetDateFormat('FULL', SITE_ID);
	}

	function direct($array, $options = array()) {
		$options = $options ? (array)$options : $this->getOptions();
		$group = isset($options['field']) ? $options['field'] : current($options);
		$type = isset($options['type']) ? $options['type'] : null;
		$result = $this->_group($array, $group, $type);

		return $result;
	}

	function setOptions($options) {
		$this->_options = (array)$options;
	}

	function getOptions() {
		return $this->_options;
	}

	protected function _group($array, $key, $type = null) {
		$tmp = array();
		foreach ($array as $value) {
			if (!isset($value[$key])) {
				continue;
			}
			$k = $this->_prepareValue( $value[$key], $type);
			$tmp[$k][] = $value;
		}
		return $tmp;
	}

	protected function _prepareValue($value, $type) {
		switch ($type) {
			case 'date':
			case 'month':
			case 'year':
			case 'day':
				if ($value != date('U', (int)$value)) {
					$dt = ParseDateTime($value, $this->_siteFormatShort);
					$value = mktime(0,0,0,$dt['MM'],$dt['DD'],$dt['YYYY']);
				} else {
					$value = mktime(0,0,0,date('n', $value), date('j', $value), date('Y', $value));
				}

				if ($type == 'month') {
					return date('mY', $value);
				}
				if ($type == 'year') {
					return date('Y', $value);
				}
				if ($type == 'day') {
					return date('dmY', $value);
				}

				return $value;
			break;

			case 'date_full':
				$dt = ParseDateTime($value, $this->_siteFormatLong);
				return mktime($dt['HH'], $dt['HI'], $dt['SS'],$dt['MM'],$dt['DD'],$dt['YYYY']);
			break;

		}
		return $value;
	}

}


?>